'''
Created on Feb 25, 2011

@author: Chris
'''
import pickle
import sys
import os
import time
import Feature

from subprocess import *

# Add stylo to the PYTHONPATH so it can find Domain.py
sys.path.append("./stylo/")

class StyloInterface(object):
    '''
    The Stylo Interface class' main function is to provide an easy way to access Stylo's stylometry tool and submit a document for analysis. 
    This class will make direct calls to the stylo interface.
    '''


    def __init__(self):
        '''
        Constructor
        '''
        self.featureList = [] # This is the list of featureSuggestions that Stylo returns to Anonymouth after analysis
        self.document = NotImplemented # This is the document or text that is to be sent to Stylo for analysis against the corpus
        self.match = NotImplemented # This is the percent chance that Stylo has of correctly identifying the author through the sample and corpus submitted. It is gotten through Stylo after analysis
        self.isCorpusTrained=False
        
    def submit(self, documentFilename, corpusPath):
        cwd = os.getcwd()
        #if we are running a test from the testing folder, then move up a level
        if os.path.basename(cwd)=="testing":
            cwd+="/.."
        stylo = cwd + "\stylo\stylo.py"
        self.featureList = []
        outfile = 'some.txt'
        f = open(outfile, 'wb')

        #if not self.isCorpusTrained:
        #    self.trainCorpus(corpus)
        
        tempTextArea = documentFilename.getText()
        tempFile = open('tempFile.txt', 'w')
        tempFile.write(tempTextArea.get('1.0', 'end'))
        tempFile.close()
        
        output = Popen(["python", stylo, "-c", corpusPath, "-i", "../tempFile.txt", "-f", "-NGramFreq"], stdout=f)
        output.wait()
        f.close()
        self.parseOutput(outfile)
        os.remove('tempFile.txt')
        os.remove('some.txt')
        
        return self.featureList
		
    def trainCorpus(self, corpus):
        cwd = os.getcwd()
        stylo = cwd + "\stylo\stylo.py"
        output = Popen(["python", stylo, "-c", corpus, "-t", "-f", "-NGramFreq"],  stdout=PIPE)#.communicate()[0]
        output.wait()
        self.isCorpusTrained=True
		
    def parseOutput(self, file):
        infile = open(file,"r")
		#Four useless headers
        line = infile.readline()
        line = infile.readline()
        line = infile.readline()
        line = infile.readline()
        while line:
            line = infile.readline()
            if line == "":
                continue
            lineparts = line.split()
            bracketlessText = lineparts[3].strip('[')
            bracketlessText = bracketlessText.strip(']')
            feature = Feature.Feature(lineparts[0], lineparts[2], bracketlessText)
            self.featureList.append(feature)
			
    def submitDocument(self):
        """
        This method is the standard submitting option to Stylo. The document shall be submit with a
        corpus and Stylo will be able to return a FeatureSuggestions list as well as a match percentage
        """
        pass
        
    def getXMLDocument(self):
        """
        This method submits the document and the corpus for analysis but also outputs the results to an XML file for future processing and archival purposes
        """
        pass